/* Copyright (c) 2015,2016 Lucky Byte, Inc.
 */
package com.lucky_byte.pay.jar.lualib;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.luaj.vm2.LuaTable;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.Varargs;
import org.luaj.vm2.lib.TwoArgFunction;
import org.luaj.vm2.lib.VarArgFunction;

import com.lucky_byte.pay.jar.MailSender;

/**
 * 在 Lua 脚本中发送邮件
 */
public class LuaMail extends TwoArgFunction
{
	private static final Logger logger = LogManager.getLogger();

	@Override
	public LuaValue call(LuaValue modname, LuaValue env) {
		LuaValue library = tableOf();
		env.set("mail", library);

		library.set("send", new Send());
		return library;
	}

	/**
	 * 例子： send(subject, content, to, cc, attachment...)
	 *
	 * 其中前四个参数分别代表 邮件主题，邮件内容，收件人列表，抄送人列表，
	 * 其中邮件内容可以是 HTML 内容，抄送人列表可以为空。
	 *
	 * 第五个参数开始是附件，附件是文件名(绝对路径)，可以有多个.
	 */
	class Send extends VarArgFunction
	{
		@Override
		public Varargs invoke(Varargs args) {
			String subject = args.checkjstring(1);
			String content = args.checkjstring(2);
			LuaTable to_table = args.checktable(3);
			LuaTable cc_table = args.opttable(4, null);

			Map<String, String> to = new HashMap<>();
			LuaValue k = LuaValue.NIL;
			while (true) {
				Varargs kv = to_table.next(k);
				k = kv.arg1();
				if (k.isnil()) {
					break;
				}
				LuaValue v = kv.arg(2);
				if (k.isint()) {
					to.put(v.checkjstring(), v.checkjstring());
				} else {
					to.put(k.checkjstring(), v.checkjstring());
				}
			}
			Map<String, String> cc = new HashMap<>();
			if (cc_table != null) {
				k = LuaValue.NIL;
				while (true) {
					Varargs kv = cc_table.next(k);
					k = kv.arg1();
					if (k.isnil()) {
						break;
					}
					LuaValue v = kv.arg(2);
					cc.put(k.checkjstring(), v.checkjstring());
				}
			}
			List<File> attachments = new ArrayList<>();
			for (int i = 5; i <= args.narg(); i++) {
				if (args.isnil(i)) {
					break;
				}
				String filename = args.checkjstring(i);
				File file = new File(filename);
				if (!file.exists()) {
					logger.error("参数[{}]引用的文件[{}]不存在.", i, filename);
					return LuaValue.valueOf(false);
				}
				if (!file.isFile()) {
					logger.error("参数[{}]引用的文件[{}]不是一个普通文件.",
							i, filename);
					return LuaValue.valueOf(false);
				}
				attachments.add(file);
			}
			return LuaValue.valueOf(MailSender.getInstance()
					.send(subject, content, to, cc, attachments));
		}
	}

}
